package com.tanhua.admin.module.login.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.tanhua.admin.module.login.service.VerificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.time.Duration;

@Service
public class VerificationServiceImpl implements VerificationService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 验证码
     * @param uuid
     * @param code
     */
    @Override
    public void saveVerification(String uuid, String code) {
        //将验证码存入redis中,有效期5分钟
        String redisKey = "MANAGE_CAP_" + uuid;
        //System.out.println(redisKey);
        redisTemplate.opsForValue().set(redisKey, code, Duration.ofMinutes(5));
    }

    /**
     * 生成验证码
     * @param response 响应
     * @return
     */
    @Override
    public String getVerification(HttpServletResponse response) {

        OutputStream ops = null;

        //定义图形验证码的长、宽、验证码字符数、干扰元素个数
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);

        //获取随机生成的内容
        String code = captcha.getCode();
        System.out.println(code);

        try {
            //获取response的响应流
            ops = response.getOutputStream();
            //把图片放入响应流
            captcha.write(ops);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return code;
    }
}
